﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DbSharp.Framework.CaseFile;
using DbSharp.Framework.Storage;
using DbSharp.Framework.Common;

namespace DbSharp.Framework.DbObject
{
    /// <summary>
    /// Perform data pump from one database into another database
    /// </summary>
    class DataPumpActionRunner
    {
        private DataPumpSection m_PumpSection;

        public DataPumpActionRunner(DataPumpSection pumpSection)
        {
            m_PumpSection = pumpSection;
        }

        public void Run(string caseName, TransactionController transController, IStorageFactory storageFactory)
        {
            var srcStatement = m_PumpSection.PumpSrcResultsetSection.StatementDeclaration;
            var srcResultsetSection = m_PumpSection.PumpSrcResultsetSection;
            StatementRunner srcStatmentRunner = new StatementRunner(transController, srcStatement, srcResultsetSection, storageFactory, null);
            srcStatmentRunner.Run(null);

            #region Get Pump source data
            object pumpSrcData;
            List<string> listOutputFieldName;
            List<FieldMetaData> listOutputFieldMetaData;
            bool isRecordset;
            int indexInList;
            bool found = srcStatmentRunner.TryGetAssertionResultset(out pumpSrcData, out listOutputFieldName, out listOutputFieldMetaData, out isRecordset, out indexInList);
            if (found == false)
            {
                string exceptionFmt = "outputArgument of {0} section in Test Case {1} does not exist.";
                throw new DbSharpException(string.Format(exceptionFmt, "pumpSourceStatement", caseName));
            }
            var pumpSourceResult = new PumpSourceResult();
            pumpSourceResult.ResultsetData = pumpSrcData;
            pumpSourceResult.ResultsetIsScalar = !isRecordset;
            if (pumpSourceResult.ResultsetIsScalar)
            {
                var argument = srcStatmentRunner.ExecutionResult.ListScalarExecutionResult[indexInList].Argument;
                pumpSourceResult.ArgNameIfIsScalar = argument.Name;
            }
            #endregion

            var destStatement = m_PumpSection.PumpDestResultsetSection.StatementDeclaration;
            var destResultsetSection = m_PumpSection.PumpDestResultsetSection;
            StatementRunner destStatmentRunner = new StatementRunner(transController, destStatement, destResultsetSection, storageFactory, pumpSourceResult);
            destStatmentRunner.Run(null);
        }
    }
}
